package me.chenzhijun.chapter2.db;

import me.chenzhijun.chapter2.utils.PropertiesUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author chen
 * @version V1.0
 * @date 2017/9/27
 */
public final class DbUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(DbUtils.class);
    private final static String URL;
    private final static String USERNAME;
    private final static String PASSWORD;
    private final static String DRIVER;

    static {
        Properties properties = PropertiesUtils.loadProperties("config.properties");
        URL = PropertiesUtils.getString(properties, "jdbc.url");
        USERNAME = PropertiesUtils.getString(properties, "jdbc.username");
        PASSWORD = PropertiesUtils.getString(properties, "jdbc.password");
        DRIVER = properties.getProperty("jdbc.driver");
        try {
            Class.forName(properties.getProperty("jdbc.driver"));
        } catch (ClassNotFoundException e) {
            LOGGER.error("no class find:{},errorMessage:{}", properties.getProperty("jdbc.driver"), e);
        }
    }


    public static Connection getConnection() {

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            LOGGER.error("connection get fail:{}", e);
        }
        return connection;

    }

    public static void closeConnection(Connection connection) {
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOGGER.error("connection close fail:{}", e);
            }
        }
    }

    private DbUtils() {
    }
}
